package com.mr.sell.service;

import com.mr.sell.config.WechatAccountConfig;
import com.mr.sell.entity.OrderMaster;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Class: PushMessageService
 * User (作者):MRui
 * TODO (描述)：公众号消息推送service
 * Date 2018.10.04 15:00
 */
@Slf4j
@Service
public class PushMessageService {

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private WechatAccountConfig accountConfig;

    /**
    * User (作者): MRui
    * TODO (描述)：发送模板消息
    * Data：2018.10.04 15:12
    */
    public void pushOrderStatus(OrderMaster orderMaster){
        //发送消息
        try {
            WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
            wxMpTemplateMessage.setTemplateId(accountConfig.getTemplateId().get("orderStatus"));
            wxMpTemplateMessage.setToUser(orderMaster.getBuyerOpenid());

            List<WxMpTemplateData> data = Arrays.asList(
                    new WxMpTemplateData("first", "亲记得收货"),
                    new WxMpTemplateData("keyword1", "微信点餐"),
                    new WxMpTemplateData("keyword2", "18866133823"),
                    new WxMpTemplateData("keyword3", orderMaster.getOrderId()),
                    new WxMpTemplateData("keyword4", orderMaster.getOrderStatusMessage()),
                    new WxMpTemplateData("keyword5", "￥" + orderMaster.getOrderAmount()),
                    new WxMpTemplateData("remark", "欢迎下次光临")
            );

            wxMpTemplateMessage.setData(data);
            wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
        } catch (WxErrorException e) {
            log.error("[消微信模板消息] 发送失败，{}",e);
        }
    }
}
